#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <stdlib.h>
#include <sys/wait.h>

void Writer(int wfd)
{
    char c = 'a';
    size_t cnt = 0;
    while (1)
    {
        write(wfd, &c, 1);
        std::cout << "pipsize: " << ++cnt << "  -> " << c << std::endl;
        if (c == 'z' + 1)
        {
            c = 'a';
        }
        c++;
    }
}

void Reader(int rfd)
{
    char buffer[1024];
    while (1)
    {
        int n = read(rfd, buffer, 1023);
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << "Son, i get:  " << buffer << std::endl;
            sleep(1);
        }
    }
}

int main()
{
    // 打开管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if (n != 0)
    {
        std::cerr << "errno: " << errno << "err_msg: " << strerror(errno) << std::endl;
    }

    // 创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        std::cout << "我是子进程, 正在关闭不需要的fd, 要准备发消息了..." << std::endl;
        close(pipefd[0]); // 关闭读端
        Writer(pipefd[1]);
        close(pipefd[1]); // 通信结束
    }

    // 父进程
    //  father -> read
    std::cout << "我是父进程, 正在关闭不需要的fd, 要准备接收消息了~~~" << std::endl;
    close(pipefd[1]); // 关闭写端;
    sleep(10);
    Reader(pipefd[0]);

    close(pipefd[0]); // 通信完毕,关闭读端

    // 等待子进程退出
    int status = 0;                      // 获取子进程的退出信息
    pid_t rid = waitpid(id, &status, 0); // 阻塞等待子进程退出
    if (rid > 0)
    {
        std::cout << "wait success" << std::endl;
        std::cout << "quit sig is: " << (status & 0x7f) << std::endl;
        std::cout << "quit code is: " << ((status >> 8) & 0xff) << std::endl;
    }

    return 0;
}